<?php
/**
 * 消费订单提交接口
 */
namespace Api\Controller;

use Think\Controller;

class WxrechargeController extends Controller {
	public $oauth_user = array();

	public function _initialize() {
        $this->m_card_push = M("CardPush");
        $this->m_card = D("Admin/Card");
        $this->m_recharge = D("Admin/Recharge");
        $this->m_logistics = D("Admin/Logistics");

        // $_SESSION['open_id'] = 'o8j7Gt-iufItn2bk4guJR9j_QimE';
        // $_SESSION['user_token'] = 'wx';
        // $_SESSION['token_time'] = time();
        
        // dump($this->oauth_user);
	}

    public $return_code = array(
        '1000'=>'成功',
        '1001'=>'系统错误',
        '1002'=>'操作员不存在',
        '1003'=>'操作员密码错误',
        '1004'=>'操作员被锁定',
        '1005'=>'硬件号码已存在',
        '1006'=>'硬件号码不存在',
    );


    /*绑定微信卡号*/
    public function index() {
        $_SESSION['open_id'] = 'o_zBb0VibvpkIXAHo7RiLRwartPU';
        // $wechat = new \Common\Lib\wechat();
        // $this->oauth_user = $wechat->wxauth();
        // $this->assign('auth',$this->oauth_user);
        $this->display();
    }

    /*第一步*/
    public function step1_init(){
        try{
            $open_id = $_SESSION['open_id'];
            $card_data = $this->m_card_push->where(array("open_id"=>$open_id))->select();
            exit(json_encode(array('code'=>1,'msg'=>'','data'=>$card_data)));
        }catch (\Exception $e){
            exit(json_encode(array('code'=>0,'msg'=>'系统错误')));
        }
    }
    public function step1_post(){
        try{
            $card_number = trim($_REQUEST['card_number']);
            $card_info = $this->m_card->alias('c')
                ->field('c.*, l.logistics_name')
                ->join('bdt_logistics l on l.id = c.lid','left')
                ->where(array('number'=>$card_number))
                ->find();
                
            if ($card_info['is_active'] == 2) {
                exit(json_encode(array('code'=>0,'msg'=>'卡片已注销')));
            }

            exit(json_encode(array('code'=>1,'msg'=>'','data'=>$card_info)));
        }catch (\Exception $e){
            exit(json_encode(array('code'=>0,'msg'=>'系统错误')));
        }
    }

    /*第二步*/
    public function step2_post(){
        // try{
            $sale_id = 1;   // 微信充值
            $user_id = 2;   // 微信用户
            $card_number = I("post.card_number");
            $price = I("post.recharge_price");
            $vip_name = I("post.vip_name");
            $vip_phone = I("post.vip_phone");
            $vip_plate_number = I("post.vip_plate_number");
            $desc = '微信充值';
            $open_id = $_SESSION['open_id'];

            $card_info = $this->m_card->where(array('number'=>$card_number))->find();
            // if ($card_info['lid'] != $lid) {
                // 更换物流公司为个人
                // $this->m_card->where(array('number'=>$card_number))->save(array('lid'=>$lid));
                
                // $this->m_logistics->where(array('id'=>$lid))->setInc('total_card_num');
                // if ($card_info['is_active']) {
                //     $this->m_logistics->where(array('id'=>$lid))->setInc('active_card_num');
                // }
            // }

            if(empty($card_number)){
                exit(json_encode(array('code'=>0,'msg'=>'卡号不能为空！')));
            }
            if(empty($price)){
                exit(json_encode(array('code'=>0,'msg'=>'充值金额不能为空！')));
            }
            $result =  $this->m_card->pre_recharge_price($card_info['lid'], $card_number,$price,$desc,$sale_id,$user_id);
            if($result === -2){
                exit(json_encode(array('code'=>0,'msg'=>'充值失败，金额不足！')));
            }
            if($result === -3){
                exit(json_encode(array('code'=>0,'msg'=>'充值失败，充值金额不足以开卡！')));
            }
            if ($result) {
                $pay_data = [
                    'trade_type'       => 'JSAPI', // JSAPI，NATIVE，APP...
                    'body'             => '会员卡充值',
                    'detail'           => '会员卡充值',
                    'out_trade_no'     => $result['number'],
                    'total_fee'        => $result['price'] * 100, // 单位：分
                    'notify_url'       => 'http://'.$_SERVER['HTTP_HOST'].'/courseapi/order/wechat_notify',
                    'openid'           => $open_id, // trade_type=JSAPI，此参数必传，用户在商户appid下的唯一标识，
                ];

                /*微信预支付*/
                $pay_config = $this->wechat_prepare($pay_data);
                if (!$pay_config) {
                    exit($this->json_return('0','生成支付订单失败！'));
                }else{
                    $pay_config = json_decode($pay_config,true);
                }
                $data = array('pay_config'=>$pay_config,'order_number'=>$result['number'],'pay_data'=>$pay_data);

                exit(json_encode(array('code'=>1,'msg'=>'','data'=>$data)));
                // $this->success("充值成功！");
            } else {
                exit(json_encode(array('code'=>0,'msg'=>'充值失败！')));
            }
        // }catch (\Exception $e){
        //     exit(json_encode(array('code'=>0,'msg'=>'系统错误')));
        // }
        
    }
    /*第三步*/
    public function step3_init(){

    }

    public function bind_card_post(){
        
        $cards = trim($_REQUEST['cards']);
        
        if (empty($cards)) {
            exit(json_encode(array('code'=>0,'msg'=>'请输入卡号')));
        }

        $cards = explode("\n", $cards);
        $open_id = $_SESSION['open_id'];


        /*验证卡号*/
        $exist_cards = $this->m_card->where(array('number'=>array('in',$cards)))->select();
        if (empty($exist_cards)) {
            exit(json_encode(array('code'=>0,'msg'=>'卡号输入错误')));
        }

        $insert_list = array();
        // dump($exist_cards);
        foreach ($exist_cards as $_key => $_row) {
            $insert_list[] = array('open_id'=>$open_id,'card_number'=>$_row['number']);
        }
        $result = $this->m_card_push->addAll($insert_list);

        if ($result) {
            exit(json_encode(array('code'=>$result,'msg'=>'')));
        } else {
            exit(json_encode(array('code'=>0,'msg'=>'系统错误')));
        }
    }

    /*绑定的卡号列表*/
    public function bind_list() {
        try{
            $open_id = $_SESSION['open_id'];
            $card_data = $this->m_card_push->where(array("open_id"=>$open_id))->select();
            exit(json_encode(array('code'=>1,'msg'=>'','data'=>$card_data)));
        }catch (\Exception $e){
            exit(json_encode(array('code'=>0,'msg'=>'系统错误')));
        }
    }

    /*绑定的卡号列表*/
    public function unbind_card() {
        try{
            $open_id = $_SESSION['open_id'];
            $card_number = I("post.card_number");
            $flag = $this->m_card_push->where(array("open_id"=>$open_id,'card_number'=>$card_number))->delete();

            exit(json_encode(array('code'=>$flag,'msg'=>$flag?'删除成功':'删除失败')));

        }catch (\Exception $e){
            exit(json_encode(array('code'=>1001,'msg'=>'解绑失败','softid'=>'')));
        }
    }


    /**
     * 生成订单
     * @param  [type] $token     [description]
     * @param  [type] $scope     [description]
     * @param  [type] $course_id [description]
     * @param  [type] $user_id   [description]
     * @param  [type] $coupon_id [description]
     * @return [type]            [description]
     */
    private function _generate_order($token, $scope, $course_id, $user_id, $coupon_id){
        $course_info = DB::name('course')
            ->where('course_id',$course_id)
            ->find();
        $coupon_info = DB::name('course_coupon')
            ->where('coupon_id',$coupon_id)
            ->find();

        // 生成20位订单号
        $order_number = $this->_generate_order_num($token,$scope);
        // 订单状态为未支付
        $status = '0';
        // 商品价格
        $price = $course_info['price'];
        // 优惠价格
        $save_price = $coupon_info['save_price'];
        // 支付价格
        $pay_price = ceil($price * 100 - $save_price * 100) / 100;

        /*生成订单*/
        $order_data = array(
            'order_number' => $order_number,
            'course_id' => $course_id,
            'user_id' => $user_id,
            'scope' => $scope,
            'status' => $status,
            'price' => $price,
            'pay_price' => $pay_price,
            'coupon_id' => $coupon_id,
            'save_price' => $save_price,
            'created_time' => date('Y-m-d H:i:s'),
        );

        $flag = DB::name('course_order')->insert($order_data);
        if (!$flag) {
            exit(json_encode(array('code'=>0,'msg'=>'由于系统原因生成订单失败！')));
        }

        $openid = session('user.openid');
        
        
    }

    /**
     * 生成订单号： 支付渠道(1)+课程类型(4)+年(2)+月(1)+日(2)+时(5)+微秒(3)+随机数(2)
     * WA---185270535635615
     * @param  [type] $token   [description]
     * @param  [type] $scope [description]
     * @return [type]          [description]
     */
    private function _generate_order_num($token,$scope){
        $scope_arr = array(
            'wechat' => 'W',
            'alipay' => 'A',
        );
        $scope_str = isset($scope_arr[$scope]) ? $scope_arr[$scope] : '-';
        $token = str_pad($token, 4, '-');
        $order_number = $scope_str.$token.
            substr(date('Y'), 2).
            strtoupper(dechex(date('m'))).
            date('d').
            substr(time(), -5).
            substr(microtime(), -3).
            sprintf('%02d', rand(0, 99));
        return $order_number;
    }

    /**
     * 生成微信支付参数
     * @param  [type] $pay_data [description]
     * @return [type]           [description]
     *
     * wx.chooseWXPay({
            timestamp: <?= $config['timestamp'] ?>,
            nonceStr: '<?= $config['nonceStr'] ?>',
            package: '<?= $config['package'] ?>',
            signType: '<?= $config['signType'] ?>',
            paySign: '<?= $config['paySign'] ?>', // 支付签名
            success: function (res) {
                // 支付成功后的回调函数
            }
        });
     */
    private function wechat_prepare($pay_data){
        // $wechat = new \Common\Lib\wechat();
        require_once $_SERVER['DOCUMENT_ROOT']."/application/Common/Lib/wxpayAPI/wxPayApi.php";
        // $options = Config::get('wechat');

        // $pay_data = [
        //     'trade_type'       => 'JSAPI', // JSAPI，NATIVE，APP...
        //     'body'             => $course_info['title'],
        //     'detail'           => $course_info['title'],
        //     'out_trade_no'     => $order_data['order_number'],
        //     'total_fee'        => $order_data['pay_price'] * 100, // 单位：分
        //     'notify_url'       => 'http://'.$_SERVER['HTTP_HOST'].'/courseapi/order/pay_notify/wechat',
        //     'openid'           => $openid, // trade_type=JSAPI，此参数必传，用户在商户appid下的唯一标识，
        // ];

        /*微信支付，本地版*/
        \WxPayConfig::init($options);
        $tools = new \JsApiPay();
        $input = new \WxPayUnifiedOrder();
        $input->SetBody($pay_data['body']);
        $input->SetAttach($pay_data['detail']);
        $input->SetOut_trade_no($pay_data['out_trade_no']);
        $input->SetTotal_fee($pay_data['total_fee']);
        $input->SetTime_start(date("YmdHis"));//交易起始时间
        $input->SetTime_expire(date("YmdHis", time() + 86400));//交易结束时间
        $input->SetGoods_tag('');
        $input->SetNotify_url($pay_data['notify_url']);
        $input->SetTrade_type($pay_data['trade_type']);
        $input->SetOpenid($pay_data['openid']);
        $order = \WxPayApi::unifiedOrder($input);
        // unClient($pay_data['mpid']);
        if (isset($order['return_code'])) {
            if ($order['return_code'] == 'SUCCESS') {
                $jsApiParameters = $tools->GetJsApiParameters($order);

                if ($jsApiParameters == false) {
                    exit(json_encode(array('code'=>0,'msg'=>'获取API参数失败')));
                } else {
                    return $jsApiParameters;
                }
            } else {
                exit(json_encode(array('code'=>0,'msg'=>'生成支付单失败'.$order['return_code'] . $order['return_msg'])));
            }
        }
        

        // $app = new Application($options);
        // $payment = $app->payment;

        // $attributes = [
        //     'trade_type'       => 'JSAPI', // JSAPI，NATIVE，APP...
        //     'body'             => 'iPad mini 16G 白色',
        //     'detail'           => 'iPad mini 16G 白色',
        //     'out_trade_no'     => '1217752501201407033233368018',
        //     'total_fee'        => 5388, // 单位：分
        //     'notify_url'       => 'http://'.$_SERVER['HTTP_HOST'].'/courseapi/order/pay_notify/wechat',
        //     'openid'           => $openid, // trade_type=JSAPI，此参数必传，用户在商户appid下的唯一标识，
        //     // ...
        // ];

        // $order = new Order($pay_data);

        // $result = $payment->prepare($order);
        // if ($result->return_code == 'SUCCESS' && $result->result_code == 'SUCCESS'){
        //     $prepayId = $result->prepay_id;
        //  $config = $payment->configForJSSDKPayment($prepayId);
        //  return $config;
        // }else{
        //  exit($this->json_return('0','生成支付订单失败！'));
        // }
    }

    public function wechat_notify(){

        $data = file_get_contents('php://input');
        $f = file_put_contents($_SERVER['DOCUMENT_ROOT'].'/logs/wechat-notify.log', "[".date('Y-m-d H:i:s')."]".var_export($data,true).PHP_EOL,FILE_APPEND);

        /*微信支付本地版*/  
        // $xml = "<xml><appid><![CDATA[wx09d91738adff02a3]]></appid>
        // <attach><![CDATA[1280课程名称]]></attach>
        // <bank_type><![CDATA[CFT]]></bank_type>
        // <cash_fee><![CDATA[1]]></cash_fee>
        // <fee_type><![CDATA[CNY]]></fee_type>
        // <is_subscribe><![CDATA[Y]]></is_subscribe>
        // <mch_id><![CDATA[1242116702]]></mch_id>
        // <nonce_str><![CDATA[6wno0m8k465znv00ui085sxfs8n9ayz4]]></nonce_str>
        // <openid><![CDATA[oBLuduMMVhhc4UaDiYvAkO-wFxh4]]></openid>
        // <out_trade_no><![CDATA[W----186067089789787]]></out_trade_no>
        // <result_code><![CDATA[SUCCESS]]></result_code>
        // <return_code><![CDATA[SUCCESS]]></return_code>
        // <sign><![CDATA[1D8A8472571C0F265A1544D149C0C92C]]></sign>
        // <time_end><![CDATA[20180606154141]]></time_end>
        // <total_fee>1</total_fee>
        // <trade_type><![CDATA[JSAPI]]></trade_type>
        // <transaction_id><![CDATA[4200000149201806065805672146]]></transaction_id>
        // </xml>";      
        if ($xml = file_get_contents('php://input')) {
            $xml_parser = xml_parser_create();
            if (!xml_parse($xml_parser, $xml, true)) {
                xml_parser_free($xml_parser);
                $f = file_put_contents($_SERVER['DOCUMENT_ROOT'].'/logs/wechat-notify.log', "解析出错".PHP_EOL,FILE_APPEND);
                return false;
            } else {
                $notify = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
                if (isset($notify['out_trade_no'])
                    && isset($notify['openid'])
                    && isset($notify['mch_id'])
                ) {
                    // 使用通知里的 "微信支付订单号" 或者 "商户订单号" 去自己的数据库找到订单
                    $order = DB::name('course_order')->where('order_number',$notify['out_trade_no'])->find();

                    if (!$order) { // 如果订单不存在
                        $f = file_put_contents($_SERVER['DOCUMENT_ROOT'].'/logs/wechat-notify.log', "订单没找到".PHP_EOL,FILE_APPEND);
                        return 'Order not exist.'; // 告诉微信，我已经处理完了，订单没找到，别再通知我了
                    }

                    // 如果订单存在
                    // 检查订单是否已经更新过支付状态
                    if ($order['paid_time']) { // 假设订单字段“支付时间”不为空代表已经支付
                        $f = file_put_contents($_SERVER['DOCUMENT_ROOT'].'/logs/wechat-notify.log', "已支付".PHP_EOL,FILE_APPEND);
                        return 'OK'; // 已经支付成功了就不再更新了
                    }

                    $order_model = new OrderModel;
                    // 用户是否支付成功
                    if ($notify['result_code'] == 'SUCCESS') {
                        // 不是已经支付状态则修改为已经支付状态
                        $order_model->order_success($notify['out_trade_no'],$notify['transaction_id']);
                        $is_enrolled = $order_model->course_enroll($notify['out_trade_no']);

                        $f = file_put_contents($_SERVER['DOCUMENT_ROOT'].'/logs/wechat-notify.log', "支付成功".PHP_EOL,FILE_APPEND);
                    } else { // 用户支付失败
                        $order_model->order_failure($notify['out_trade_no'],$notify['transaction_id']);
                        $f = file_put_contents($_SERVER['DOCUMENT_ROOT'].'/logs/wechat-notify.log', "支付失败".PHP_EOL,FILE_APPEND);
                    }
                    
                    return 'OK';
                }
            }
        }else{
            $f = file_put_contents($_SERVER['DOCUMENT_ROOT'].'/logs/wechat-notify.log', "未获取到".PHP_EOL,FILE_APPEND);
        }
    }
}

